package cn.sc.allinpay.allfavour.base.connect.socket;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import cn.pai.common.log.Loger;
import cn.sc.allinpay.allfavour.base.connect.socket.connectfactory.ConnectionFactory;
import cn.sc.allinpay.allfavour.base.connect.socket.connection.Connection;

/**
 * 通信类
 *
 * @author panyi
 */
public class OkSocket {

    /**
     * handler 主线程handler
     */
    private final Handler mDelivery;
    /**
     * new ThreadPoolExecutor(2, 8, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(2));
     * corePoolSize:核心线程数
     * maxPoolSize:当线程数大于或等于核心线程，且任务队列已满时，线程池会创建新的线程，直到线程数量达到maxPoolSize
     * keepAliveTime:当线程空闲时间达到keepAliveTime，该线程会退出，直到线程数量等于corePoolSize
     * allowCoreThreadTimeout:是否允许核心线程空闲退出，默认值为false
     * queueCapacity:任务队列容量
     */
    private ExecutorService executor;
    private ConnectionFactory connectionFactory;

    private static class OkSocketHolder {
        private static final OkSocket INSTANCE = new OkSocket();
    }

    public static final OkSocket getInstance() {
        return OkSocketHolder.INSTANCE;
    }

    /**
     * 初始化构造器
     * @param factory
     */
    public static void initialize(ConnectionFactory factory) {
        //初始化socket通信
        OkSocket.getInstance().init(factory);
    }

    private OkSocket() {
        mDelivery = new Handler(Looper.getMainLooper());
        executor = new ThreadPoolExecutor(2, 6, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(2));
    }

    public void init(ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    public void send(final String data, final OnResponse onResponse) {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Loger.d("请求参数：" + data);
                Connection connection = connectionFactory.create();
                try {
                    connection.connect(null);
                    connection.send(data.getBytes("utf-8"));
                    byte[] rsp = connection.receive();
                    final String resp = new String(rsp, "utf-8");
                    Loger.d("请求响应：" + resp);
                    Loger.d("---------------okSocket end---------------------");
                    mDelivery.post(new Runnable() {
                        @Override
                        public void run() {
                            onResponse.onResponse(resp);
                        }
                    });
                } catch (final Exception e) {
                    Loger.d("---------------okSocket end---------------------");
                    mDelivery.post(new Runnable() {
                        @Override
                        public void run() {
                            onResponse.onError(e.getMessage());
                        }
                    });
                } finally {
                    try {
                        Loger.d("---------------关闭okSocket--------------------");
                        connection.disconnect();
                    } catch (final Exception e) {
                        mDelivery.post(new Runnable() {
                            @Override
                            public void run() {
                                onResponse.onError(e.getMessage());
                            }
                        });
                    }
                }
            }
        });
    }

    public interface OnResponse {
        void onResponse(String resp);

        void onError(String msg);
    }
}
